<template>
  <div class="user-manage">
    <div class="page-header">
      <div class="header-title">用户管理</div>
    </div>

    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键字">
          <el-input v-model="searchForm.keyword" placeholder="用户名/手机/邮箱"></el-input>
        </el-form-item>
        <el-form-item label="用户角色">
          <el-select v-model="searchForm.role" placeholder="请选择" clearable>
            <el-option label="普通用户" value="user"></el-option>
            <el-option label="管理员" value="admin"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="启用" :value="1"></el-option>
            <el-option label="禁用" :value="0"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="userList"
      border
      style="width: 100%"
      v-loading="loading"
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="username" label="用户名" width="120"></el-table-column>
      <el-table-column label="头像" width="80">
        <template slot-scope="scope">
          <el-avatar :size="40" :src="scope.row.avatar"></el-avatar>
        </template>
      </el-table-column>
      <el-table-column prop="realName" label="真实姓名" width="120"></el-table-column>
      <el-table-column prop="phone" label="手机号" width="130"></el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="180"></el-table-column>
      <el-table-column prop="role" label="角色" width="100">
        <template slot-scope="scope">
          <el-tag :type="scope.row.role === 'admin' ? 'danger' : 'primary'">
            {{ scope.row.role === 'admin' ? '管理员' : '用户' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" width="180">
        <template slot-scope="scope">
          {{ formatDate(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="status" label="状态" width="100">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="handleStatusChange(scope.row)"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template slot-scope="scope">
          <el-button 
            size="mini" 
            type="primary"
            @click="viewUserOrders(scope.row.id)"
          >
            订单
          </el-button>
          <el-button 
            size="mini" 
            :type="scope.row.role === 'admin' ? 'danger' : 'info'"
            :disabled="scope.row.id === currentUserId"
            @click="toggleUserRole(scope.row)"
          >
            {{ scope.row.role === 'admin' ? '取消管理员' : '设为管理员' }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="currentPage"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>
    
    <!-- 用户订单对话框 -->
    <el-dialog title="用户订单" :visible.sync="orderDialogVisible" width="80%">
      <div class="user-order-info" v-if="selectedUser">
        <div class="user-info">
          <el-avatar :size="50" :src="selectedUser.avatar"></el-avatar>
          <div class="user-details">
            <div class="user-name">{{ selectedUser.username }}</div>
            <div class="user-meta">{{ selectedUser.phone }} | {{ selectedUser.email }}</div>
          </div>
        </div>
      </div>
      
      <el-table
        :data="userOrders"
        border
        style="width: 100%; margin-top: 20px;"
        v-loading="orderLoading"
      >
        <el-table-column prop="orderNo" label="订单号" width="180"></el-table-column>
        <el-table-column prop="restaurantName" label="餐厅名称"></el-table-column>
        <el-table-column prop="payAmount" label="金额" width="100">
          <template slot-scope="scope">
            ¥{{ scope.row.payAmount }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template slot-scope="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="下单时间" width="180">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" @click="viewOrderDetail(scope.row.id)">查看详情</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="no-data" v-if="userOrders.length === 0 && !orderLoading">
        该用户暂无订单
      </div>
      
      <div slot="footer" class="dialog-footer">
        <el-button @click="orderDialogVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'UserManage',
  data() {
    return {
      loading: false,
      userList: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      searchForm: {
        keyword: '',
        role: '',
        status: ''
      },
      currentUserId: null, // 当前登录的用户ID
      orderDialogVisible: false,
      selectedUser: null,
      userOrders: [],
      orderLoading: false
    }
  },
  created() {
    this.getCurrentUser()
    this.fetchUserList()
  },
  methods: {
    getCurrentUser() {
      this.$http.get('/user/info')
        .then(response => {
          const { data } = response.data
          this.currentUserId = data.id
        })
    },
    fetchUserList() {
      this.loading = true
      
      const params = {
        page: this.currentPage,
        size: this.pageSize,
        keyword: this.searchForm.keyword,
        role: this.searchForm.role,
        status: this.searchForm.status
      }
      
      this.$http.get('/admin/user/list', { params })
        .then(response => {
          const { data } = response.data
          this.userList = data.records
          this.total = data.total
        })
        .catch(error => {
          this.$message.error('获取用户列表失败')
          console.error('获取用户列表失败', error)
        })
        .finally(() => {
          this.loading = false
        })
    },
    handleSearch() {
      this.currentPage = 1
      this.fetchUserList()
    },
    resetSearch() {
      this.searchForm = {
        keyword: '',
        role: '',
        status: ''
      }
      this.handleSearch()
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchUserList()
    },
    handleCurrentChange() {
      this.fetchUserList()
    },
    formatDate(dateString) {
      if (!dateString) return ''
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    handleStatusChange(user) {
      // 不允许禁用自己
      if (user.id === this.currentUserId && user.status === 0) {
        this.$message.error('不能禁用当前登录的账号')
        user.status = 1
        return
      }
      
      this.$http.put(`/admin/user/${user.id}/status`, null, {
        params: { status: user.status }
      })
        .then(() => {
          this.$message.success(`用户状态已${user.status === 1 ? '启用' : '禁用'}`)
        })
        .catch(error => {
          // 恢复状态
          user.status = user.status === 1 ? 0 : 1
          this.$message.error((error.response && error.response.data && error.response.data.message) || '更新状态失败')
        })
    },
    toggleUserRole(user) {
      // 不允许修改自己的角色
      if (user.id === this.currentUserId) {
        this.$message.error('不能修改当前登录的账号角色')
        return
      }
      
      const newRole = user.role === 'admin' ? 'user' : 'admin'
      const confirmMsg = newRole === 'admin' 
        ? '确认将该用户设置为管理员？'
        : '确认取消该用户的管理员权限？'
      
      this.$confirm(confirmMsg, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 实际项目中应调用API更新用户角色
        this.$http.put(`/admin/user/${user.id}/role`, { role: newRole })
          .then(() => {
            user.role = newRole
            this.$message.success('用户角色更新成功')
          })
          .catch(error => {
            this.$message.error((error.response && error.response.data && error.response.data.message) || '更新角色失败')
          })
      }).catch(() => {})
    },
    viewUserOrders(userId) {
      this.orderLoading = true
      
      // 获取用户信息
      this.$http.get(`/admin/user/${userId}`)
        .then(response => {
          this.selectedUser = response.data.data
          this.orderDialogVisible = true
          
          // 获取用户订单
          return this.$http.get('/admin/order/list', {
            params: {
              userId: userId,
              page: 1,
              size: 10
            }
          })
        })
        .then(response => {
          const { data } = response.data
          this.userOrders = data.records
        })
        .catch(error => {
          this.$message.error('获取用户信息失败')
          console.error('获取用户信息失败', error)
        })
        .finally(() => {
          this.orderLoading = false
        })
    },
    viewOrderDetail(orderId) {
      // 关闭当前对话框
      this.orderDialogVisible = false
      
      // 跳转到订单详情页
      this.$router.push({
        path: '/admin/order',
        query: { id: orderId }
      })
    },
    getStatusText(status) {
      const statusMap = {
        0: '待支付',
        1: '已支付',
        2: '配送中',
        3: '已完成',
        4: '已取消'
      }
      return statusMap[status] || '未知状态'
    },
    getStatusType(status) {
      const typeMap = {
        0: 'warning',
        1: 'primary',
        2: 'success',
        3: 'success',
        4: 'info'
      }
      return typeMap[status] || 'info'
    }
  }
}
</script>

<style scoped>
.user-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-title {
  font-size: 20px;
  font-weight: bold;
}

.search-bar {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.pagination-container {
  margin-top: 20px;
  text-align: center;
}

.user-order-info {
  padding: 10px;
  background-color: #f5f7fa;
  border-radius: 4px;
  margin-bottom: 20px;
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 15px;
}

.user-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.user-meta {
  font-size: 14px;
  color: #909399;
}

.no-data {
  text-align: center;
  padding: 50px 0;
  color: #909399;
}
</style>
